import { Navigate, RouteObject, useLocation, useNavigate } from "react-router-dom"
import { useDispatch, useSelector } from 'react-redux';
import { ReactNode, Suspense, lazy, useEffect } from "react";
import Login from "@/views/Login";
import Home from "@/views/Home";
const Admin = lazy(() => import('@/views/Admin/Admin'))

const  WithAuthGuard = ({ children }: {children:ReactNode}) => {
  const navigate = useNavigate();
  const location = useLocation();
  const state = useSelector((state:any) => state.token)
  useEffect(() => {
    if (!state.token) {
      navigate('/login');
    }
  }, [navigate, location]);
  return <> {children}</>
}

const LayoutComponent = ({ children }: any) => {
  return (
    <Suspense fallback={""}>
      {children}
    </Suspense>
  );
};

const routes: RouteObject[] = [
  {
    path: "/",
    element: <Navigate to="/admin" />,
  },
  {
    path: "/",
    element: <Home />,
    children: [
      {
        path: "admin",
        element: <WithAuthGuard><LayoutComponent><Admin /></LayoutComponent></WithAuthGuard>,
      },
      {
        path: "user",
        element: <WithAuthGuard><div>user</div></WithAuthGuard>,
      },
      {
        path: "*",
        element: <Navigate to="/admin" />,
      }
    ]
  },
  {
    path: "/login",
    element: <Login />,
  }
]

export default routes;